import re
from django.contrib.auth.backends import ModelBackend

from .models import User




def get_user_mobile(account):
    """判断是用户名还是手机号登录"""

    try:
        if re.match(r'^1[3-9]\d{9}', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None

    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request=None, username = None,password=None, **credentials):

        user = get_user_mobile(username)

        if user and user.check_password(password):
            return user


